<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="orderCode" label="订单号" />
          <el-option value="contactPhone" label="客户电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmAddress" label="客户地址" />
          <el-option value="transactor" label="下单人" />
          <el-option value="remark" label="备注" />
          <el-option value="goodsDesc" label="商品描述" />
          <el-option value="ownerName" label="处理人" />
          <el-option value="saleMan" label="销售员" />
        </el-select>
        <el-input v-model="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="来源:">
        <el-select v-model="query.orderSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderSourceMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="user_qtype" style="width: 170px; margin-right: 2px;" @change="qtypeChange">
          <el-option value="ownerId" label="处理人" />
          <el-option value="transactId" label="下单人" />
        </el-select>
        <el-select v-model="user_qtype_value" :loading="$loadingPlugin.getOwnerList || $loadingPlugin.getTransactorList" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in userQtypeList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型:">
        <el-select v-model="query.orderFlagSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderFlagMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否补单:">
        <el-select v-model="query.isRemedy">
          <el-option label="是" :value="1" />
          <el-option label="否" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="下单时间" value="transactTime" />
          <el-option label="签收时间" value="signTime" />
          <el-option label="回执时间" value="reCheckDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="query.orderStatusSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select v-model="query.csmTypeSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态:">
        <el-select v-model="query.payStatus" placeholder="请选择">
          <el-option
            v-for="item in payStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:">
        <el-select v-model="query.paymentMethodSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in paymentMethodMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回执状态:">
        <el-select v-model="query.reStatus" placeholder="请选择">
          <el-option
            v-for="item in payStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" :loading="$loadingPlugin.fetchData" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="9" :loading="$loadingPlugin.exportFile" type="primary" icon="el-icon-folder-opened" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <csm-location ref="csmLocation" />
    <csm-detail ref="csmDetail" />
    <order-images ref="orderImages" />
    <order-detail ref="orderDetail" :payment-method-map="paymentMethodMap" :pay-status-map="payStatusMap" />
    <pay-detail ref="payDetail" />
    <species-amount ref="speciesAmount" />
    <remark-order ref="remarkOrder" />
    <press-order ref="pressOrder" />
    <back-order ref="backOrder" />
    <back-order-apply ref="backOrderApply" />
    <press-order-report ref="pressOrderReport" />
    <sign-order ref="signOrder" :transactor-list="transactorList" :payment-method-map="paymentMethodMap" />
    <transfer-order ref="transferOrder" />
    <back-goods ref="backGoods" />
    <receipt-confirm ref="receiptConfirm" :payment-method-map="paymentMethodMap" />
    <flow-info ref="flowInfo" />
  </div>
</template>

<script>
  import {
    queryOwnerList,
    queryTransactorList,
    queryOrderManageList,
    queryMap,
    queryOrderListExport,
    queryExportDomain,
    queryOrderbillReturnParam
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { orderStatusObj, payStatusObj } from '@/utils/map'
  import CsmLocation from '../../components/CsmLocation'
  import OrderImages from './components/OrderImages'
  import CsmDetail from '../../components/CsmDetailModal'
  import OrderDetail from './components/OrderDetails'
  import PayDetail from './components/PayDetail'
  import SpeciesAmount from './components/SpeciesAmount'
  import RemarkOrder from './components/Remark'
  import PressOrder from '../../components/PressOrderModal'
  import BackOrder from './components/BackOrder'
  import PressOrderReport from '../../components/PressOrderReport'
  import SignOrder from './components/SignOrder'
  import TransferOrder from '../../components/TransferOrderModal'
  import BackGoods from './components/BackGoods'
  import ReceiptConfirm from './components/ReceiptConfirm'
  import FlowInfo from './components/OrderFlow'
  import BackOrderApply from './components/BackOrderApply'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'orderManage',
    components: {
      PressOrderReport, CsmLocation, OrderImages, CsmDetail, OrderDetail, PayDetail, SpeciesAmount, RemarkOrder, PressOrder, BackOrder, SignOrder,
      TransferOrder, BackGoods, ReceiptConfirm, FlowInfo, BackOrderApply
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        currentOrg: null,
        ownerList: [],
        transactorList: [],
        qtype: 'contactPhone',
        txt: '',
        orderSourceMap: [],
        orderFlagMap: [],
        user_qtype: 'ownerId',
        user_qtype_value: '',
        userQtypeList: [], // 下单人或处理人列表
        dateType: 'transactTime',
        date: [moment().startOf('day'), moment().endOf('day')],
        orderStatusMap: [],
        customerTypeMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        reStatusMap: [],
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          orderSource: [0],
          orderFlagSource: [0],
          isRemedy: '',
          orderStatusSource: [0],
          csmTypeSource: [0],
          payStatus: '',
          paymentMethodSource: [0],
          reStatus: ''
        },
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ]),
      column: function() {
        return [
          {
            prop: 'imageUrl',
            label: '图片',
            width: 50,
            align: 'center',
            render: (h, { row }) => {
              if ((row.intSpare6 >> 7 & 0x01) > 0) {
                return <span onClick={() => this.showImage(row)} style='color:green;cursor:pointer;'><i class='el-icon-picture' /></span>
              } else {
                return ''
              }
            }
          },
          {
            prop: 'orderCode',
            label: '订单号',
            width: 110,
            render: (h, { row }) => <el-link onClick={() => this.openOrderDetail(row)}>{row.orderCode}</el-link>
          },
          {
            prop: 'transactor',
            label: '下单人'
          },
          {
            prop: 'ownerName',
            label: '处理人'
          },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 220,
            render: (h, { row }) => <span>{row.lon && <i onClick={() => this.openLocation(row)} class='el-icon-location' style='color: #F56C6C;cursor: pointer;'/>}{ row.csmAddress }</span>
          },
          {
            prop: 'csmName',
            label: '客户名称',
            render: (h, { row }) => <el-link onClick={() => this.openCsmDetail(row)}>{row.csmName}</el-link>
          },
          {
            prop: 'contactPhone',
            label: '联系电话',
            width: 110
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: 160
          },
          {
            prop: 'transactTime',
            label: '下单时间',
            width: 140,
            render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'urgeCount',
            label: '催单次数',
            render: (h, { row }) => row.urgeCount ? <el-link onClick={() => this.openPressOrderReport(row)}>{row.urgeCount}</el-link> : <span>{row.urgeCount}</span>
          },
          {
            prop: 'orderStatus',
            label: '状态',
            render: (h, { row }) => <span style={orderStatusObj[row.orderStatus]}>{ row.csmType && formatColumnMap(this.orderStatusMap, 'value', row.orderStatus, 'desc') }</span>
          },
          {
            prop: 'orderFlag',
            label: '订单类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.orderFlagMap, 'value', row.orderFlag, 'desc') }</span>
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'fromPlat',
            label: '订单来源',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.orderSourceMap, 'value', row.fromPlat, 'desc') }</span>
          },
          {
            prop: 'csmPhone',
            width: 110,
            label: '呼入电话'
          },
          {
            prop: 'contact',
            label: '联系人'
          },
          {
            prop: 'goodsCount',
            label: '商品总数',
            align: 'right'
          },
          {
            prop: 'goodsDesc',
            label: '商品描述',
            width: 150
          },
          {
            prop: 'decimalSpare4',
            label: '订单总额',
            align: 'right',
            render: (h, { row }) => <el-link onClick={() => this.openPayDetail()}>{ row.decimalSpare4 && row.decimalSpare4.toFixed(2) }</el-link>
          },
          {
            prop: 'decimalSpare1',
            label: '总配送费',
            align: 'right',
            render: (h, { row }) => <span>{ row.decimalSpare1 && row.decimalSpare1.toFixed(2) }</span>
          },
          {
            prop: 'decimalSpare2',
            label: '总上楼费',
            align: 'right',
            render: (h, { row }) => <span>{ row.decimalSpare2 && row.decimalSpare2.toFixed(2) }</span>
          },
          {
            prop: 'decimalSpare3',
            label: '总服务费',
            align: 'right',
            render: (h, { row }) => <span>{ row.decimalSpare3 && row.decimalSpare3.toFixed(2) }</span>
          },
          {
            prop: 'totalFee4',
            label: '优惠金额',
            align: 'right',
            render: (h, { row }) => <el-link onClick={() => this.openSpeciesAmount()}>{ row.totalFee4 && row.totalFee4.toFixed(2) }</el-link>
          },
          {
            prop: 'treceivables',
            label: '应收金额',
            align: 'right',
            render: (h, { row }) => <el-link onClick={() => this.openPayDetail()}>{ row.treceivables && row.treceivables.toFixed(2) }</el-link>
          },
          {
            prop: 'taccReceivable',
            label: '实收金额',
            align: 'right',
            render: (h, { row }) => <el-link onClick={() => this.openPayDetail()}>{ row.taccReceivable && row.taccReceivable.toFixed(2) }</el-link>
          },
          {
            prop: 'payStatus',
            label: '支付状态',
            render: (h, { row }) => <span style={payStatusObj[row.payStatus]}>{ row.payStatus ? formatColumnMap(this.payStatusMap, 'value', row.payStatus, 'desc') : '未支付' }</span>
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.paymentMethodMap, 'value', row.paymentMethod, 'desc') }</span>
          },
          {
            prop: 'isInvoice',
            label: '需发票',
            align: 'center',
            width: 70,
            render: (h, { row }) => row.isInvoice && <i class='el-icon-success' style='color: #F56C6C;' />
          },
          {
            prop: 'reStatus',
            label: '回执状态',
            render: (h, { row }) => <span>{ row.reStatus || row.reStatus === 0 ? formatColumnMap(this.reStatusMap, 'value', row.reStatus, 'desc') : '无需回执' }</span>
          },
          {
            prop: 'isUrgent',
            label: '加急',
            align: 'center',
            width: 70,
            render: (h, { row }) => row.isUrgent && <i class='el-icon-success' style='color: #F56C6C;' />
          },
          {
            prop: 'isPickUp',
            label: '自提',
            align: 'center',
            width: 70,
            render: (h, { row }) => row.isPickUp && <i class='el-icon-success' style='color: #F56C6C;' />
          },
          {
            prop: 'intSpare1',
            label: '托管',
            render: (h, { row }) => row.intSpare1 && <i class='el-icon-success' style='color: #F56C6C;' />
          },
          {
            prop: 'lastUrgeDt',
            label: '最后催单时间',
            width: 140,
            render: (h, { row }) => <span>{ row.lastUrgeDt && parseTime(row.lastUrgeDt, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'reCheckDt',
            label: '回执时间',
            width: 140,
            render: (h, { row }) => <span>{ row.reCheckDt && parseTime(row.reCheckDt, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'dateTimeSpare2',
            label: '上次安检时间',
            width: 140,
            render: (h, { row }) => <span>{ row.dateTimeSpare2 && parseTime(row.dateTimeSpare2, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'gasCheckFlag',
            label: '是否已安检',
            align: 'center',
            width: 100,
            render: (h, { row }) => {
              let v = row.intSpare6 || 0
              v = v >> 0 & 0x01
              if (v === 1) {
                return <span>是</span>
              }
            }
          },
          {
            prop: 'isRemedy',
            label: '是否补单',
            render: (h, { row }) => {
              let v = row.intSpare6 || 0
              v = v >> 5 & 0x01
              if (v === 1) {
                return <span>是</span>
              } else if (v === 0) {
                return <span>否</span>
              }
            }
          },
          {
            prop: 'dateTimeSpare3',
            label: '派送时间',
            width: 140,
            render: (h, { row }) => <span>{ row.dateTimeSpare3 && parseTime(row.dateTimeSpare3, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'appointmentDt',
            label: '配送时效区间',
            width: 150,
            render: (h, { row }) => {
              if (row.appointmentDt && moment(row.appointmentDt).format('YYYYMMDD') < 20170316) {
                return moment(row.appointmentDt).format('YY-MM-DD HH:mm') || ''
              }
              if (!row.appointmentDt && !row.dateTimeSpare1) {
                return ''
              } else {
                let color = '#444'
                let title = '正常'
                if (row.dateTimeSpare1) {
                  if (row.orderStatus >= 1 && row.orderStatus < 7) {
                    const m = moment(row.dateTimeSpare1).valueOf() -
                      new Date().getTime()
                    if (m <= 0) { // 已超时，红色
                      color = '#ff0000'
                      title = '已超时'
                    } else if (m / 1000 / 60 < row.intSpare3) { // 未超时但达到预警时间，黄色
                      color = '#ed912e'
                      title = '已达预警时限'
                    }
                  }
                }
                const day = moment(row.appointmentDt || row.dateTimeSpare1).format('MM-DD    ')
                if (row.appointmentDt && !row.dateTimeSpare1) {
                  const time1 = moment(row.appointmentDt).format('HH:mm')
                  if (row.orderStatus === 1) {
                    return <span style={color} title={title}>预约:{day}{time1}之后</span>
                  } else {
                    return <span style={color} title={title}>{day}{time1}之后</span>
                  }
                } else if (!row.appointmentDt && row.dateTimeSpare1) {
                  const time2 = moment(row.dateTimeSpare1).format('HH:mm')
                  if (row.orderStatus === 1) {
                    return <span style={color} title={title}>预约:{day}{time2}之前</span>
                  } else {
                    return <span style={color} title={title}>{day}{time2}之后</span>
                  }
                } else {
                  const time1 = moment(row.appointmentDt).format('HH:mm')
                  const time2 = moment(row.dateTimeSpare1).format('HH:mm')
                  if (row.orderStatus === 1) {
                    return <span style={color} title={title}>预约:{day}{time1}~{time2}</span>
                  } else {
                    return <span style={color} title={title}>{day}{time1}~{time2}</span>
                  }
                }
              }
            }
          },
          {
            prop: 'intSpare4',
            label: '配送超时时间',
            width: 120,
            render: (h, { row }) => {
              if (row.intSpare4) {
                const h = Math.floor(row.intSpare4 / 60)
                const m = row.intSpare4 % 60
                if (h >= 1) {
                  if (m > 0) {
                    return h + '小时' + m + '分钟'
                  } else {
                    return h + '小时'
                  }
                } else {
                  return m + '分钟'
                }
              }
              return ''
            }
          },
          {
            prop: 'signDt',
            label: '签收时间',
            width: 140,
            render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'signUserName',
            label: '签收人'
          },
          {
            prop: 'signUserIdNumber',
            label: '签收人身份证号',
            width: 150
          },
          {
            prop: 'saleMan',
            label: '销售员'
          },
          {
            prop: 'relBackGas',
            label: '回收气量'
          },
          {
            prop: 'generalGas',
            label: '实送气量'
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.orderStatus === 2 && <el-link size='mini' onClick={() => this.openTransferOrder(row, $index)}>转派</el-link>}
                  {(row.orderStatus === 2 || row.orderStatus === 5) && <el-link size='mini' onClick={() => this.openPressOrder(row, $index)}>催单</el-link>}
                  {(row.orderStatus === 2 || row.orderStatus === 5) && <el-link size='mini' onClick={() => this.openBackOrder(row, $index)}>退单</el-link>}
                  {(row.orderStatus === 2 || row.orderStatus === 5) && <el-link size='mini' onClick={() => this.openSignOrder(row, $index)}>签单</el-link>}
                  {row.orderStatus === 2 && <el-link size='mini' onClick={() => this.openReceiptConfirm(row, $index)}>回执确认</el-link>}
                  <el-link size='mini' onClick={() => this.openRemark(row)}>备注</el-link>
                  {(row.orderStatus === 10 && row.reStatus !== 2) && <el-link size='mini' type='danger' onClick={() => this.openBackGoods(row, $index)}>退货</el-link>}
                  <el-link size='mini' onClick={() => this.openFlow(row)}>流转信息</el-link>
                  <el-link size='mini' onClick={() => this.print(row)}>打印</el-link>
                </div>
              )
            }
          }
        ]
      }
    },
    watch: {
      'query.orderSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderSource.length === this.orderSourceMap.length) this.query.orderSource = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderFlagSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderFlagSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderFlagSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderFlagSource.length === this.orderFlagMap.length) this.query.orderFlagSource = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderStatusSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderStatusSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderStatusSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderStatusSource.length === this.orderStatusMap.length) this.query.orderStatusSource = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.csmTypeSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.csmTypeSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.csmTypeSource.splice(val.indexOf(0), 1)
        }
        if (this.query.csmTypeSource.length === this.customerTypeMap.length) this.query.csmTypeSource = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.paymentMethodSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.paymentMethodSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.paymentMethodSource.splice(val.indexOf(0), 1)
        }
        if (this.query.paymentMethodSource.length === this.paymentMethodMap.length) this.query.paymentMethodSource = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    async created() {
      await Promise.all([this.getExportDomain(), this.getTreeData(), this.getTransactorList(), this.getOwnerList(), this.queryOptionsMap()])
      this.qtypeChange('ownerId')
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        if (this.query.orderSource[0] === 0) query.orderSource = []
        query[this.user_qtype] = this.user_qtype_value
        if (this.query.orderFlagSource[0] === 0) query.orderFlagSource = []
        if (this.query.orderStatusSource[0] === 0) query.orderStatusSource = []
        if (this.query.csmTypeSource[0] === 0) query.csmTypeSource = []
        if (this.query.paymentMethodSource[0] === 0) query.paymentMethodSource = []
        if (this.date && this.date.length === 2) {
          query[this.dateType] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
        }
        const res = await queryOrderManageList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.getOwnerList()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }), mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }), mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }), mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }), mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }), mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }), mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })])
        this.orderStatusMap = res1.data.filter(item => item.value !== 5) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.orderSourceMap = res7.data // 订单来源
      },
      // 获取处理人列表
      async getOwnerList() {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const orgId = this.currentOrg ? this.currentOrg.orgId : -1
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownerList = res.data
        if (this.user_qtype === 'ownerId') this.userQtypeList = this.ownerList
        else this.userQtypeList = this.transactorList
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      // 处理人或下单人选择
      qtypeChange(value) {
        if (value === 'ownerId') this.userQtypeList = this.ownerList
        else this.userQtypeList = this.transactorList
      },
      // 点击催单次数
      async openPressOrderReport(row) {
        await this.$refs.pressOrderReport.open({ billCode: row.orderCode, billType: 1 })
      },
      // 点击图片
      async showImage(row) {
        await this.$refs.orderImages.open(row)
      },
      // 点击地址
      async openLocation(row) {
        await this.$refs.csmLocation.open(row)
      },
      // 点击客户名称
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 点击订单号
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row)
      },
      // 点击订单总额
      async openPayDetail() {
        await this.$refs.payDetail.open()
      },
      // 点击优惠金额
      async openSpeciesAmount() {
        await this.$refs.speciesAmount.open()
      },
      // 点击备注
      async openRemark(row) {
        await this.$refs.remarkOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击流转信息
      async openFlow(row) {
        await this.$refs.flowInfo.open(row.orderCode)
      },
      // 点击转派
      async openTransferOrder(row) {
        await this.$refs.transferOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击催单
      async openPressOrder(row) {
        await this.$refs.pressOrder.open({ billCode: row.orderCode, billType: 1 })
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击退单
      async openBackOrder(row) {
        const res = await queryOrderbillReturnParam({
          orderCode: row.orderCode,
          ownerId: row.ownerId
        })
        const showCheck = JSON.parse(res.data.showCheck)
        if (showCheck) await this.$refs.backOrderApply.open(res.data)
        else await this.$refs.backOrder.open(res.data)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击签单
      async openSignOrder(row) {
        await this.$refs.signOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击回执确认
      async openReceiptConfirm(row) {
        await this.$refs.receiptConfirm.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击退货
      async openBackGoods(row) {
        await this.$refs.backGoods.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async scoresMerge() {
        await this.$refs.scoresMerge.open()
      },
      async infoCircul() {
        // 参数为订单号
        await this.$refs.infoCircul.open('176697')
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryOrderListExport({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7 || row.orderStatus === 3) { // 7:已退单 3:退单申请中
          return 'danger-row'
        }
        if (row.orderStatus === 9 || row.orderStatus === 12) { // 9:退货申请中 12:已退货
          return 'giveup-row'
        }
        return ''
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #F99;
}
/deep/ .el-table tr.giveup-row {
  background: #fc9;
}
</style>
